import data
import opParse
import opProc
    
def proc_func_stats(fp:data.FileParse):
    if len(fp.stats) == 0:
        return
    ops = fp.funcs[-1].ops
    stats = data.StatOp()
    stats.stat = list(fp.stats)
    stats.complete = True
    if not ops[-1].complete:
        ops[-1].stat.append(stats)
    else:
        ops.append(stats)
    fp.stats.clear()


def proc_ops_stats(fp:data.FileParse):
    if len(fp.stats) == 0:
        return
    
    statOp = data.StatOp()
    statOp.stat = list(fp.stats)
    statOp.complete = True
    if not fp.ops[-1].complete:
        fp.ops[-1].append(statOp)
    else:
        fp.ops.append(statOp)
    fp.stats.clear()


def proc_func_def(line, fp: data.FileParse):
    proc_func_stats(fp)
    line = line.strip()
    funcs = {
        "var": opParse.parse_var,
        "if": opParse.parse_if,
        "else_if": opParse.parse_elif,
        "loop": opParse.parse_loop,
        "end_loop": opParse.parse_endloop,
        "end_if": opParse.parse_endif, 
        "end_macro": opParse.parse_endmacro
    }

    if line.startswith("defmacro"):
        opParse.parse_defmacro(line[8:], fp.funcs)
    else:
        for key,func in funcs.items():
            key_len = len(key)
            if line[0 : key_len] == key:
                func(line[key_len:], fp.funcs[-1].ops)
                break
    
    
def proc_op_def(line, fp: data.FileParse):
    line = line.strip()
    funcs = {
        "var":      opParse.parse_var,
        "if":       opParse.parse_if,
        "else_if":  opParse.parse_elif,
        "end_if":   opParse.parse_endif, 
        "loop":     opParse.parse_loop,
        "end_loop": opParse.parse_endloop,
        "macro":    opParse.parse_macro
    }

    for key,func in funcs.items():
        key_len = len(key)
        if line[0 : key_len] == key:
            func(line[key_len:], fp.ops)


def proc_func(line, fp: data.FileParse):
    if line[0] =='#':
        proc_func_def(line[1:], fp)
    else:
        fp.stats.append(line)

def proc_op(line, fp: data.FileParse):
    if line[0] =='#':
        proc_op_def(line[1:], fp)
    else:
        fp.stats.append(line)


def parse_proc(line, fp):
    if fp.op_flag:
        proc_op(line, fp)
    else:
        if line == "begin":
            fp.op_flag = True
        elif line == "end":
            fp.op_flag = False
        else:
            proc_func(line, fp)

def parse(fp: data.FileParse):
    with open("ty.rx", "r") as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip()
            if (len(line) == 0) :
                continue 
            parse_proc(line, fp)

    print("parse finish.")


def createDeck(deck: data.Deck, fp: data.FileParse):
    for op in fp.ops:
        type = op.OpType()
        func = opProc.check_proc_func(type)
        func(deck, op, fp)
    print("create deck finish.")